package com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.resistEarthquakesPE.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzfxqh.base.dict.service.DictItemService;
import com.css.fxfzfxqh.base.dict.service.DictService;
import com.css.fxfzfxqh.base.dict.viewobjects.DictEntityVo;
import com.css.fxfzfxqh.common.rest.JcsjRestManager;
import com.css.fxfzfxqh.common.utils.UpdateUtil;
import com.css.fxfzfxqh.constants.FxfzConstants;
import com.css.fxfzfxqh.constants.YNEnum;
import com.css.fxfzfxqh.modules.buildingIndividual.entity.BuildingIndividualEntity;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.exceptions.BizException;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.exceptions.StrategyFactoryException;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.model.param.QueryByVersionParam;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.service.FxqhBuildingGridDataVersionService;
import com.css.fxfzfxqh.modules.buildings.VO.CurveVo;
import com.css.fxfzfxqh.modules.buildings.calculationTasks.entity.CalculationTasks;
import com.css.fxfzfxqh.modules.buildings.calculationTasks.entity.DistrictEntity;
import com.css.fxfzfxqh.modules.buildings.calculationTasks.entity.YSXMainTable;
import com.css.fxfzfxqh.modules.buildings.calculationTasks.repository.CalculationTasksRepository;
import com.css.fxfzfxqh.modules.buildings.calculationTasks.service.CalculationTasksService;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.casualtiesDE.entity.BuildingVulnerability;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.casualtiesDE.entity.PCC;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.casualtiesDE.vo.Grid13VO;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.resistEarthquakesDE.entity.PCCName;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.resistEarthquakesDE.param.AssessParam;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.util.Tools;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.util.YSXUtil;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.publicOperate.entity.PsHazardDataValue;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.publicOperate.service.DistrictService;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.publicOperate.service.PublicOperateService;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.publicOperate.vo.BasicLibraryVo;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.resistEarthquakesPE.entity.ResistEarthquakesPE;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.resistEarthquakesPE.entity.ResistEarthquakesPECalculation;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.resistEarthquakesPE.param.PETasksParam;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.resistEarthquakesPE.param.ResistEarthquakesPECalculationParam;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.resistEarthquakesPE.repository.ResistEarthquakesPERepository;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.resistEarthquakesPE.service.ResistEarthquakesPEService;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.resistEarthquakesPE.vo.ResistEarthquakesPCCPEVO;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.resistEarthquakesPE.vo.ResistEarthquakesXYPEVO;
import com.css.fxfzfxqh.modules.singleIndexRiskZoning.model.entity.FxqhAssessPdQhResult;
import com.css.fxfzfxqh.modules.util.Calculation;
import com.css.fxfzfxqh.modules.util.ExcelUtil;
import com.css.fxfzfxqh.modules.util.ResistEarthquakesEnum;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.util.YSXEntity;
import com.css.fxfzfxqh.modules.util.hypergraph.service.HypergraphService;
import com.css.fxfzfxqh.modules.util.repository.PccRepository;
import com.css.fxfzfxqh.modules.util.repository.YSXRepository;
import com.css.fxfzfxqh.util.*;
import com.css.fxfzfxqh.web.PlatformSessionContext;
import com.css.fxfzfxqh.zcpt.sys.entity.SUser;
import com.css.fxfzfxqh.zcpt.sys.service.SUserService;
import com.css.fxfzfxqh.zcpt.sys.service.SysAreaService;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFDataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Author: zhangSongRui
 * @CreateTime: 2023/06/16
 * @Description: 抗震能力_概率评估Service
 */
@Slf4j
@Service
public class ResistEarthquakesPEServiceImpl implements ResistEarthquakesPEService {
    @Resource
    private ResistEarthquakesPERepository resistEarthquakesPERepository;
    @Resource
    private SysAreaService sysAreaService;
    @Resource
    SUserService sUserService;
    @Resource
    PccRepository pccRepository;
    @Resource
    DictService dictService;
    @Resource
    DictItemService dictItemService;
    @Resource
    FxqhBuildingGridDataVersionService fxqhBuildingGridDataVersionService;
    @Resource
    private PublicOperateService publicOperateService;
    @Resource
    CalculationTasksService calculationTasksService;
    @Resource
    private CalculationTasksRepository calculationTasksRepository;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    YSXUtil ysxUtil;
    @Resource
    private DistrictService districtService;
    @Resource
    HypergraphService hypergraphService;

    @Override
    public void addAssess(ResistEarthquakesPE param) {
        String user = sUserService.getSUser(PlatformSessionContext.getUserID());
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        param.setId(UUIDGenerator.getUUID());
        param.setCreateUser(sUser.getCreateUser());
        param.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        param.setDelFlag(YNEnum.N.toString());
        param.setGeom(param.getCoordinateRange());
        //创建人单位
        param.setCompany(sUser.getOrgName());
        //写入省市县
        setCCP(param);
        resistEarthquakesPERepository.addAssess(param);
    }

    //写入省市县
    private void setCCP(ResistEarthquakesPE param) {
        List<PCC> pccList1 = new ArrayList<>();
        List<PCC> pccList = param.getList();
        if (pccList.size() != 0) {
            for (PCC pcc : pccList) {
                if (PlatformObjectUtils.isNotEmpty(pcc.getPpName())) {
                    if (PlatformObjectUtils.isEmpty(pcc.getCityName())) {
                        String childArea1 = sysAreaService.getChildAreaById(pcc.getPid());
                        List<PCCName> objects1 = JSON.parseArray(childArea1, PCCName.class);
                        for (PCCName pccName1 : objects1) {
                            String childArea2 = sysAreaService.getChildAreaById(pccName1.getId());
                            List<PCCName> objects2 = JSON.parseArray(childArea2, PCCName.class);
                            for (PCCName pccName2 : objects2) {
                                PCC pcc1 = new PCC();
                                pcc1.setAssessId(param.getId());
                                pcc1.setUuid(UUIDGenerator.getUUID());
                                pcc1.setPid(pcc.getPid());
                                pcc1.setPpName(pcc.getPpName());
                                pcc1.setCid(pccName1.getId());
                                pcc1.setCityName(pccName1.getName());
                                pcc1.setName(pccName2.getName());
                                pcc1.setId(pccName2.getId());
                                pccList1.add(pcc1);
                            }
                        }
                    } else {
                        if (PlatformObjectUtils.isEmpty(pcc.getName())) {
                            String childArea = sysAreaService.getChildAreaById(pcc.getCid());
                            List<PCCName> objects = JSON.parseArray(childArea, PCCName.class);
                            for (PCCName pccName : objects) {
                                PCC pcc1 = new PCC();
                                pcc1.setAssessId(param.getId());
                                pcc1.setUuid(UUIDGenerator.getUUID());
                                pcc1.setPid(pcc.getPid());
                                pcc1.setPpName(pcc.getPpName());
                                pcc1.setCid(pcc.getCid());
                                pcc1.setCityName(pcc.getCityName());
                                pcc1.setName(pccName.getName());
                                pcc1.setId(pccName.getId());
                                pccList1.add(pcc1);
                            }
                        } else {
                            pcc.setAssessId(param.getId());
                            pcc.setUuid(UUIDGenerator.getUUID());
                            pccList1.add(pcc);
                        }
                    }
                } else {
                    pcc.setAssessId(param.getId());
                    pcc.setUuid(UUIDGenerator.getUUID());
                    pccList1.add(pcc);
                }
            }
            pccRepository.batchSavePCC(pccList1);
        }
    }

    //根基id查询
    @Override
    public ResistEarthquakesPE findById(String id) {
        ResistEarthquakesPE byId = resistEarthquakesPERepository.findById(id);
        List<PCC> list = pccRepository.queryToponym(byId.getId());
        byId.setList(list);
        return byId;
    }

    //修改评估记录
    @Override
    public void upDateAssess(ResistEarthquakesPE param) {
        param.setUpdateUser(PlatformSessionContext.getUserID());
        param.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        resistEarthquakesPERepository.upDateAssess(param);
    }

    //获取评估记录code
    @Override
    public String getCode(ResistEarthquakesPE param) {
        //抗震能力确定评估
        StringBuilder code = new StringBuilder("JZW-FW-GL");
        if (param.getHouseDataFlag().equals("0")) {
            //单体
            code.append("-DT");
        } else if (param.getHouseDataFlag().equals("1")) {
            //网格
            code.append("-WG");
        }
        if (StringUtils.isEmpty(param.getCoordinateRange())) {
            //如果经纬度范围为空
            code.append("-QH");
        } else {
            code.append("-QD");
        }
        if (param.getSeismicInputMode().equals("0")) {
            //烈度
            code.append("-LD");
        } else if (param.getSeismicInputMode().equals("1")) {
            //概率水准
            code.append("-GL");
        } else if (param.getSeismicInputMode().equals("2")) {
            //地震影响场
            code.append("-YX");
        }
        String[] split1 = code.toString().split("-");
        if (split1.length != 6) {
            return code.toString();
        }
        //查询最近一次code
        String oldCode = resistEarthquakesPERepository.queryLatest(code);
        if (StringUtils.isEmpty(oldCode)) {
            code.append("-0001");
        } else {
            String[] split = oldCode.split("-");
            code.append("-").append(getNext(split[6]));
        }
        return code.toString();
    }

    /****
     * 从哪里开始计数 比如startValue=2，则会从003,004,005等
     * @param startValue
     * @return
     */
    public String getNext(String startValue) {
        Integer i = Integer.valueOf(startValue);
        String format = String.format("%04d", i + 1);
        return format;
    }

    //分页
    @Override
    public Map<String, Object> getPage(int curPage, int pageSize, AssessParam param) {
        Map<String, Object> page = resistEarthquakesPERepository.getPage(curPage, pageSize, param);
        List<ResistEarthquakesPE> list = (List<ResistEarthquakesPE>) page.get("rows");
        for (ResistEarthquakesPE obj : list) {
            List<PCC> pccs = pccRepository.queryToponym(obj.getId());
            obj.setList(pccs);
        }
        page.put("rows", list);
        return page;
    }

    @Override
    public void calculation(PETasksParam param) {
        //获取任务
        CalculationTasks tasks = calculationTasksRepository.findById(param.getTaskId());
        List<PCC> list = pccRepository.queryToponym(tasks.getId());
        tasks.setList(list);
        //第一步获取T年列表
//        List<DictEntityVo> dictItemByDictId = dictItemService.getDictItemByDictId("jzwglgwlx");
        ArrayList<ResistEarthquakesPECalculation> listParam = new ArrayList<>();
        //写入四个破坏状态,从轻微破坏到倒塌
        if (tasks.getLdPga().equals("1")) {
            String[] split = tasks.getYear().split(",");
            for (String s : split) {
                //PGA不循环直接算出所有破坏状态
                ResistEarthquakesPECalculation obj = new ResistEarthquakesPECalculation();
                obj.setAssessId(tasks.getId());
                obj.setAssessCode(tasks.getAssessCode());
                //写入T年
                obj.setYears(s);
                listParam.add(obj);
            }
        } else {
            String[] split = tasks.getYear().split(",");
            for (String s : split) {
                for (int j = 1; j < 6; j++) {
                    ResistEarthquakesPECalculation obj = new ResistEarthquakesPECalculation();
                    obj.setAssessId(tasks.getId());
                    obj.setAssessCode(tasks.getAssessCode());
                    //写入T年
                    obj.setYears(s);
                    //破坏状态
                    obj.setDamageDegree("pgcd" + j);
                    listParam.add(obj);
                }
            }
        }
        //循环计算所有T年
        for (ResistEarthquakesPECalculation rCalculation : listParam) {
            //0为烈度,1为pga  超越概率转化成发生概率
            if (tasks.getLdPga().equals("0")) {
                //发生概率地震危险性烈度
                try {
                    FSLDCalculation(rCalculation, tasks);
                    log.info("烈度计算结束");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                //发生概率地震危险性PGA
                try {
                    FSPGACalculation(rCalculation, tasks);
                    log.info("PGA计算结束");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        //修改计算进度
        if (tasks.getSeismicInputMode().equals("3")) {
            calculationTasksRepository.updateFSProgress(tasks.getId(), "评估", "结构破坏");
        } else {
            calculationTasksRepository.updateCYProgress(tasks.getId(), "评估", "结构破坏");
        }
        boolean bool = hypergraphService.getWorkspaceReload("fxqh_resist_earthquakes_calculation_pd");
    }

    //发生概率地震危险性PGA计算
    private void FSPGACalculation(ResistEarthquakesPECalculation rCalculation, CalculationTasks tasks) throws Exception {
        //根据所有省市县获取省市县geom
        String unionGeomByCode = null;
        //如果根据省市县评估则取省市县,如果根据地图圈选则默认写入一条
        if (tasks.getRadio2().equals("0")) {
            //0为省市区县
            //根据所有省市县获取省市县geom
            unionGeomByCode = publicOperateService.getUnionGeomByCode(tasks.getList());
        } else if (tasks.getRadio2().equals("1")) {
            //写入地图圈选geom
            unionGeomByCode = tasks.getCoordinateRange();
        }
        Map<String, List<PsHazardDataValue>> mapVXX = new HashMap<>();
        if (tasks.getSeismicInputMode().equals("3")) {
            //该省市县下面的所有发生概率  格网
            List<PsHazardDataValue> psHazardDataValueList = publicOperateService.getPsHazardDataValueList("0", unionGeomByCode);
            for (PsHazardDataValue obj : psHazardDataValueList) {
                String extends1 = obj.getId();
                List<PsHazardDataValue> newList;
                if (mapVXX.containsKey(extends1)) {
                    newList = mapVXX.get(extends1);
                } else {
                    newList = new ArrayList<>();
                }
                newList.add(obj);
                mapVXX.put(extends1, newList);
            }
        } else {
            String type = "1";
            if (tasks.getHouseDataFlag().equals("1")) {
                type = "0";
            }
            //重新组装 格网  超越概率
            Table<String, List<String>, List<BigDecimal>> stringMapMap = publicOperateService.transition2(unionGeomByCode, tasks.getBeyondProbabilisticVersion(), "0");
            for (String rowKey : stringMapMap.rowKeySet()) {
                List<PsHazardDataValue> psHazardDataValues = new ArrayList<>();
                //循环横行
                for (List<String> columnKey : stringMapMap.columnKeySet()) {
                    List<BigDecimal> bigDecimals = stringMapMap.get(rowKey, columnKey);
                    if (null == bigDecimals) {
                        continue;
                    }
                    //循环纵行
                    for (int i = 0; i < columnKey.size(); i++) {
                        PsHazardDataValue psHazardDataValue = new PsHazardDataValue();
                        psHazardDataValue.setImValue(columnKey.get(i));
                        psHazardDataValue.setFImValue(bigDecimals.get(i));
                        psHazardDataValues.add(psHazardDataValue);
                    }
                }
                mapVXX.put(rowKey, psHazardDataValues);
            }
        }
        //十三个结构类型的值的list;计算用
        List<Calculation> calculationList = new ArrayList<>();
        if (tasks.getHouseDataFlag().equals("1")) {
            //房屋格网
            //第一步根据版本号查询十三个房屋类型
            List<DictEntityVo> dictItemByDictId = dictItemService.getDictItemByDictCode("jzwglgwlx");
            for (DictEntityVo dictEntityVo : dictItemByDictId) {
                log.info("开始计算" + dictEntityVo.getDictItemCode());
                //烈度的公里网格
                List<Grid13VO> gridDataList = calculationTasksRepository.getGlGwDate(tasks.getId(), dictEntityVo.getDictItemCode());
                //如果有数据则循环计算
                if (gridDataList != null) {
                    for (Grid13VO obj : gridDataList) {
                        //根据省市县获取对应的PGA函数
                        Map<String, Map<String,Table<String,BigDecimal, CurveVo>>> centerValue1 = new HashMap<>();
                        publicOperateService.getCenterValue1(obj.getProvince(), obj.getCity(), obj.getCounty(),tasks.getYsxVersion(),tasks.getId(),centerValue1);
                        //总面积*设防占比之和
                        BigDecimal totalArea = BigDecimal.ZERO;
                        //该结构类型下,所有设防状态 下的ysx PGA
                        Map<String, Table<String,BigDecimal, CurveVo>> stringMapMap =
                                centerValue1.get(ysxUtil.getStructureType(obj.getDictionary()));
                        //根据geom获取对应的发生概率
                        List<PsHazardDataValue> psHazardDataValues = mapVXX.get(obj.getExtends1());
                        if (null == psHazardDataValues) {
                            continue;
                        }
                        if (null == stringMapMap) {
                            continue;
                        }
                        //计算
//                        Calculation calculation = PGAcompute(obj, stringMapMap, psHazardDataValues);
//                        calculationList.add(calculation);
                    }
                }
                //获取
                log.info("计算结束" + dictEntityVo.getDictItemCode());
            }
            //保存
            List<ResistEarthquakesPECalculation> conditionValue = getConditionValue(calculationList, tasks, rCalculation);
            //入库
            if (conditionValue.size() > 0) {
                resistEarthquakesPERepository.deleteCalculationByQuery(conditionValue.get(0));
                resistEarthquakesPERepository.batchCalculation(conditionValue);
            }
        } else {
            List<ResistEarthquakesPECalculation> conditionValue = new ArrayList<>();
            //房屋单体数据
            List<BuildingIndividualEntity> all = calculationTasksRepository.getMonomerDate(tasks.getId());
            for (BuildingIndividualEntity obj : all) {
                List<PsHazardDataValue> psHazardDataValues = null;
                if (tasks.getSeismicInputMode().equals("3")) {
                    //根据房屋单体经纬度获取对应发生概率
                    psHazardDataValues = publicOperateService.getFSGLbyLonAndLat(obj.getLongitude(), obj.getLatitude(), "0");
                } else {
                    //根据房屋单体经纬度获取对应超越概率
                    for (Map.Entry<String, List<PsHazardDataValue>> entry : mapVXX.entrySet()) {
                        Boolean boo = resistEarthquakesPERepository.getSTIntersects(entry.getKey(), obj.getLongitude(), obj.getLatitude());
                        if (boo) {
                            psHazardDataValues = entry.getValue();
                            break;
                        }
                    }
                }
                //获取结构类型
                String type = getType(obj.getStructureType1(), obj.getStructureType2());
                //根据省市县和房屋结构类型获取对应的PGA函数
                Map<String, Map<String, BasicLibraryVo.stateValue>> stringMapMap = null;
                        //= publicOperateService.getCenterValue1(obj.getProvince(), obj.getCity(), obj.getCounty()).get(type);
                if (null == psHazardDataValues) {
                    continue;
                }
                if (null == stringMapMap) {
                    continue;
                }
                //将房屋单体转换成13VO
                Grid13VO grid13VO = get13VO(obj);
                //计算
                Calculation calculation = PGAcompute(grid13VO, stringMapMap, psHazardDataValues);
                //单体直接计算,无需13个合并 S(砖混)*【0.999969*（f1(0.01）-f2(0.01))+0.961678*（f1(0.15）-f2(0.15))+。。。+0.0012*（f1(0.95）-f2(0.95))】/S
                BigDecimal area = calculation.getArea();
                //获取4个计算值list
                List<BigDecimal> pgAv4List = getPGAv4List(calculation);
                for (int i = 0; i < pgAv4List.size(); i++) {
                    BigDecimal bigDecimal = pgAv4List.get(i);
                    //单体最终计算结果
                    BigDecimal p1 = bigDecimal.divideToIntegralValue(area).setScale(6, RoundingMode.DOWN);
                    ResistEarthquakesPECalculation pECalculation = new ResistEarthquakesPECalculation();
                    //主键
                    pECalculation.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                    //评估记录id
                    pECalculation.setAssessId(tasks.getId());
                    //评估记录code
                    pECalculation.setAssessCode(tasks.getAssessCode());
                    //省市县
                    pECalculation.setProvinceName(obj.getProvince());
                    pECalculation.setCityName(obj.getCity());
                    pECalculation.setCountyName(obj.getCounty());
                    //格网/单体虚拟id
                    pECalculation.setGeographyId(obj.getId());
                    //破坏状态
                    pECalculation.setDamageDegree("pgcd" + (i + 1));
                    //计算值
                    pECalculation.setCalculatedValueP1(p1);
                    //修正值
                    pECalculation.setCorrectionValueP1(p1);
                    //概率值p (T)
                    pECalculation.setPt(p1.multiply(BigDecimal.valueOf(Double.parseDouble(rCalculation.getYears()))));
                    //T年
                    pECalculation.setYears(rCalculation.getYears());
                    //写入面积
                    pECalculation.setArea(area);

                    pECalculation.setCreateUser(PlatformSessionContext.getUserID());
                    pECalculation.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
                    pECalculation.setDelFlag(YNEnum.N.toString());
                    conditionValue.add(pECalculation);
                }
            }
            //入库
            if (conditionValue.size() > 0) {
                resistEarthquakesPERepository.deleteCalculationByQuery(conditionValue.get(0));
                resistEarthquakesPERepository.batchCalculation(conditionValue);
            }
        }
    }

    //获取pga四个计算值list
    private List<BigDecimal> getPGAv4List(Calculation calculation) {
        BigDecimal v1 = calculation.getV1();
        BigDecimal v2 = calculation.getV1();
        BigDecimal v3 = calculation.getV1();
        BigDecimal v4 = calculation.getV1();
        ArrayList<BigDecimal> list = new ArrayList<>();
        list.add(v1);
        list.add(v2);
        list.add(v3);
        list.add(v4);
        return list;
    }

    //PGA计算
    private Calculation PGAcompute(Grid13VO obj, Map<String, Map<String, BasicLibraryVo.stateValue>> stringMapMap, List<PsHazardDataValue> psHazardDataValues) {
        //总面积*设防占比之和
        BigDecimal totalArea = BigDecimal.ZERO;
        //根据不同的设防状态循环计算该格网下四个破坏状态的值
        //S(砖混)*【0.999969*（f1(0.01）-f2(0.01))+0.961678*（f1(0.15）-f2(0.15))+。。。+0.0012*（f1(0.95）-f2(0.95))】/S
        BigDecimal v1 = BigDecimal.ZERO;
        BigDecimal v2 = BigDecimal.ZERO;
        BigDecimal v3 = BigDecimal.ZERO;
        BigDecimal v4 = BigDecimal.ZERO;
        //如果不设防不等于0
        int fang = 0;
        if (obj.getSfIntensity() >= 0.0009) {
            ArrayList<BigDecimal> list = getV("未设防", v1, v2, v3, v4, stringMapMap, psHazardDataValues);
            v1 = v1.add(list.get(0));
            v2 = v2.add(list.get(1));
            v3 = v3.add(list.get(2));
            v4 = v4.add(list.get(3));
            totalArea = totalArea.add(getArea(obj.getSfIntensity(), BigDecimal.valueOf(obj.getTotalArea())));
        } else {
            fang = fang + 1;
        }
        //如果现设防烈度_6度房屋面积占比不等于0
        if (obj.getSfIntensity6() >= 0.0009) {
            ArrayList<BigDecimal> list = getV("未设防", v1, v2, v3, v4, stringMapMap, psHazardDataValues);
            v1 = v1.add(list.get(0));
            v2 = v2.add(list.get(1));
            v3 = v3.add(list.get(2));
            v4 = v4.add(list.get(3));
            totalArea = totalArea.add(getArea(obj.getSfIntensity6(), BigDecimal.valueOf(obj.getTotalArea())));
        } else {
            fang = fang + 1;
        }
        //如果现设防烈度_7度房屋面积占比不等于0
        if (obj.getSfIntensity7() >= 0.0009) {
            ArrayList<BigDecimal> list = getV("未设防", v1, v2, v3, v4, stringMapMap, psHazardDataValues);
            v1 = v1.add(list.get(0));
            v2 = v2.add(list.get(1));
            v3 = v3.add(list.get(2));
            v4 = v4.add(list.get(3));
            totalArea = totalArea.add(getArea(obj.getSfIntensity7(), BigDecimal.valueOf(obj.getTotalArea())));
        } else {
            fang = fang + 1;
        }
        //如果现设防烈度_8度房屋面积占比不等于0
        if (obj.getSfIntensity8() >= 0.0009) {
            ArrayList<BigDecimal> list = getV("未设防", v1, v2, v3, v4, stringMapMap, psHazardDataValues);
            v1 = v1.add(list.get(0));
            v2 = v2.add(list.get(1));
            v3 = v3.add(list.get(2));
            v4 = v4.add(list.get(3));
            totalArea = totalArea.add(getArea(obj.getSfIntensity8(), BigDecimal.valueOf(obj.getTotalArea())));
        } else {
            fang = fang + 1;
        }
        //如果现设防烈度_9度房屋面积占比不等于0
        if (obj.getSfIntensity9() >= 0.0009) {
            ArrayList<BigDecimal> list = getV("未设防", v1, v2, v3, v4, stringMapMap, psHazardDataValues);
            v1 = v1.add(list.get(0));
            v2 = v2.add(list.get(1));
            v3 = v3.add(list.get(2));
            v4 = v4.add(list.get(3));
            totalArea = totalArea.add(getArea(obj.getSfIntensity9(), BigDecimal.valueOf(obj.getTotalArea())));
        } else {
            fang = fang + 1;
        }
        //如果没有一个设防结构有值则默认为未设防100%,并且在有总面积的时候计算
        if (fang == 5 & obj.getTotalArea() >= 0.01) {
            ArrayList<BigDecimal> list = getV("未设防", v1, v2, v3, v4, stringMapMap, psHazardDataValues);
            v1 = v1.add(list.get(0));
            v2 = v2.add(list.get(1));
            v3 = v3.add(list.get(2));
            v4 = v4.add(list.get(3));
            totalArea = totalArea.add(BigDecimal.valueOf(obj.getTotalArea()));
        }
        //计算单个结构S(砖混)*【0.999969*（f2(0.01）-f3(0.01))+0.961678*（f2(0.15）-f3(0.15))+。。。+0.0012*（f2(0.95）-f3(0.95))】
        v1 = totalArea.multiply(v1).setScale(6, RoundingMode.DOWN);
        v2 = totalArea.multiply(v2).setScale(6, RoundingMode.DOWN);
        v3 = totalArea.multiply(v3).setScale(6, RoundingMode.DOWN);
        v4 = totalArea.multiply(v4).setScale(6, RoundingMode.DOWN);
        Calculation calculation = new Calculation();
        //格网id
        calculation.setExtends1(obj.getExtends1());
        //省市县
        calculation.setProvince(obj.getProvince());
        calculation.setCity(obj.getCity());
        calculation.setCounty(obj.getCounty());
        //计算值
        calculation.setV1(v1);
        calculation.setV2(v2);
        calculation.setV3(v3);
        calculation.setV4(v4);
        //单个面积
        calculation.setArea(BigDecimal.valueOf(obj.getTotalArea()));
        calculation.setGeom(obj.getGeom());
        return calculation;
    }

    //获取面积
    private BigDecimal getArea(Double sfIntensity, BigDecimal totalArea) {
        //计算当前设防状态的面积
        //获取当前设防状态占比
        BigDecimal bigDecimal = BigDecimal.valueOf(sfIntensity).divide(BigDecimal.valueOf(100)).setScale(8, BigDecimal.ROUND_DOWN);
        BigDecimal multiply = totalArea.multiply(bigDecimal);
        //面积
        return multiply;
    }

    //计算并赋值
    private ArrayList<BigDecimal> getV(String type, BigDecimal v1, BigDecimal v2, BigDecimal v3, BigDecimal v4, Map<String, Map<String, BasicLibraryVo.stateValue>> stringMapMap, List<PsHazardDataValue> psHazardDataValues) {
        //获取到对应设防烈度的易损性值
        Map<String, BasicLibraryVo.stateValue> phMap = stringMapMap.get(type);
        //四个破坏程度下的易损性曲线
        BasicLibraryVo.stateValue qwph = phMap.get("轻微破坏");
        BasicLibraryVo.stateValue zdph = phMap.get("中等破坏");
        BasicLibraryVo.stateValue yzph = phMap.get("严重破坏");
        BasicLibraryVo.stateValue hh = phMap.get("倒塌");
        //循环发生概率   0.999969*（f2(0.01）-f3(0.01))+0.961678*（f2(0.15）-f3(0.15))+。。。+0.0012*（f2(0.95）-f3(0.95))】
        for (PsHazardDataValue psHazardDataValue : psHazardDataValues) {
            String imValue = psHazardDataValue.getImValue();
            BigDecimal fImValue = psHazardDataValue.getFImValue();
            BigDecimal f1 = publicOperateService.getFuntionValue(qwph.getMr().toString(), qwph.getBr().toString(), imValue);
            BigDecimal f2 = publicOperateService.getFuntionValue(zdph.getMr().toString(), zdph.getBr().toString(), imValue);
            BigDecimal f3 = publicOperateService.getFuntionValue(yzph.getMr().toString(), yzph.getBr().toString(), imValue);
            BigDecimal f4 = publicOperateService.getFuntionValue(hh.getMr().toString(), hh.getBr().toString(), imValue);
            //0.999969*((f1(0.01）-f2(0.01))
            v1 = v1.add(fImValue.multiply(f1.subtract(f2)).setScale(6, BigDecimal.ROUND_DOWN));
            v2 = v2.add(fImValue.multiply(f2.subtract(f3)).setScale(6, BigDecimal.ROUND_DOWN));
            v3 = v3.add(fImValue.multiply(f3.subtract(f4)).setScale(6, BigDecimal.ROUND_DOWN));
            v4 = v4.add(fImValue.multiply(f4).setScale(6, BigDecimal.ROUND_DOWN));
        }
        ArrayList<BigDecimal> list = new ArrayList<>();
        list.add(v1);
        list.add(v2);
        list.add(v3);
        list.add(v4);
        return list;
    }

    //发生概率地震危险性烈度计算
    private void FSLDCalculation(ResistEarthquakesPECalculation rCalculation, CalculationTasks tasks) throws Exception, BizException {
        //根据所有省市县获取省市县geom
        String unionGeomByCode = null;
        if (tasks.getRadio2().equals("0")) {
            //0为省市区县
            //根据所有省市县获取省市县geom
            unionGeomByCode = publicOperateService.getUnionGeomByCode(tasks.getList());
            //得到该区域内所有的省市县。


        } else if (tasks.getRadio2().equals("1")) {
            //1为地图圈选
            //写入地图圈选geom
            unionGeomByCode = tasks.getCoordinateRange();
        }
        //发生概率
        Map<String, List<PsHazardDataValue>> mapVXX = new HashMap<>();
        //超越概率
        Table<String, List<String>, List<BigDecimal>> stringMapMap = HashBasedTable.create();
        if (tasks.getSeismicInputMode().equals("3")) {
            //该省市县下面的所有危险性
            List<PsHazardDataValue> psHazardDataValueList = publicOperateService.getPsHazardDataValueList("1", unionGeomByCode);
            for (PsHazardDataValue obj : psHazardDataValueList) {
                String extends1 = obj.getId();
                List<PsHazardDataValue> newList;
                if (mapVXX.containsKey(extends1)) {
                    newList = mapVXX.get(extends1);
                } else {
                    newList = new ArrayList<>();
                }
                newList.add(obj);
                mapVXX.put(extends1, newList);
            }
        } else {
            String type = "1";
            if (tasks.getHouseDataFlag().equals("1")) {
                type = "0";
            }
            //重新组装
            stringMapMap = publicOperateService.transition1(unionGeomByCode, tasks.getBeyondProbabilisticVersion(), type);
        }
        //将危险性根据格网id合并
        //十三个结构类型的值的list;计算用
        List<Calculation> calculationList = new ArrayList<>();
        if (tasks.getHouseDataFlag().equals("1")) {
            //房屋格网
            //第一步根据版本号查询十三个房屋类型
            List<DictEntityVo> dictItemByDictId = dictItemService.getDictItemByDictCode("jzwglgwlx");
            //获取到区域内的所有省市县；然后获取该区域内的所有易损性。
            List<DistrictEntity> districtEntities = districtService.queryProvinceCityCountyNameCodeListByGeomText(unionGeomByCode);
            Map<String, Map<String, List<YSXMainTable>>> stringListMap = new HashMap<>();
            for (DistrictEntity entity : districtEntities) {
                if (!stringListMap.containsKey(entity.getProvince() + "_" + entity.getCity() + "_" + entity.getCounty())) {
                    Map<String, List<YSXMainTable>> temStringListMap = ysxUtil.ysxEncapsulationNew(tasks.getId(),
                            entity.getProvince(), entity.getCity(), entity.getCounty());
                    stringListMap.put(entity.getProvince() + "_" + entity.getCity() + "_" + entity.getCounty(), temStringListMap);
                }
                //无易损性数据则则跳过计算
                if (PlatformObjectUtils.isEmpty(stringListMap)) {
                    continue;
                }
            }
            for (DictEntityVo dictEntityVo : dictItemByDictId) {
                //结构类型(字典值)
                String dictItemCode = dictEntityVo.getDictItemCode();
                //破坏程度
                String damageDegree = dictService.getValueByDictCodeAndKey("pgcd", rCalculation.getDamageDegree());
                log.info("开始计算" + dictEntityVo.getDictItemCode());
                //烈度的公里网格
                List<Grid13VO> gridDataList = calculationTasksRepository.getGlGwDate(tasks.getId(), dictEntityVo.getDictItemCode());
                //如果有数据则循环计算
                if (gridDataList != null) {
                    for (Grid13VO obj : gridDataList) {
                        //计算出概率数据
                        //当前结构类型的概率计算值
                        BigDecimal result = BigDecimal.ZERO;
                        //总面积*设防占比之和
                        BigDecimal totalArea = BigDecimal.ZERO;
                        List<PsHazardDataValue> psHazardDataValues = new ArrayList<>();
                        //获取发生概率
                        if (tasks.getSeismicInputMode().equals("3")) {
                            psHazardDataValues = mapVXX.get(obj.getExtends1());
                        } else {
                            //超越概率转换
                            Map<List<String>, List<BigDecimal>> row = stringMapMap.row(obj.getExtends1());
                            if (null == row) {
                            } else {
                                for (Map.Entry<List<String>, List<BigDecimal>> row1 : row.entrySet()) {
                                    for (int i = 0; i < row1.getKey().size(); i++) {
                                        PsHazardDataValue psHazardDataValue = new PsHazardDataValue();
                                        psHazardDataValue.setImValue(row1.getKey().get(i));
                                        psHazardDataValue.setFImValue(row1.getValue().get(i));
                                        psHazardDataValues.add(psHazardDataValue);
                                    }
                                }
                            }
                        }

                        if (null == psHazardDataValues) {
                            continue;
                        }
                        //计算 计算的时候传入易损性数据
                        Map<String, List<YSXMainTable>> stringListMap1 = stringListMap.get(obj.getProvince() + "_" + obj.getCity() + "_" + obj.getCounty());
                        //如果没有易损性就跳过计算
                        if (PlatformObjectUtils.isEmpty(stringListMap1)) {
                            continue;
                        }
                        //结构类型_毁坏程度_烈度
                      /*  String structureTypeName = ySXUtil.getStructureType(dictItemCode);
                        String conditionName = ySXUtil.ldConversion(condition);
                        stringListMap1.get()*/
                        List<BigDecimal> bigDecimals = calculationByFortification(obj, psHazardDataValues,
                                dictItemCode, damageDegree, result, totalArea, tasks, stringListMap);
                        result = bigDecimals.get(0);
                        totalArea = bigDecimals.get(1);
                        //计算单个结构最终结构P(砖混)=S(砖混)*（P(VI)+P(VII)。。。+P(XII)）
                        BigDecimal multiply = totalArea.multiply(result);
                        Calculation calculation = new Calculation();
                        //格网id
                        calculation.setExtends1(obj.getExtends1());
                        //省市县
                        calculation.setProvince(obj.getProvince());
                        calculation.setCity(obj.getCity());
                        calculation.setCounty(obj.getCounty());
                        //计算值
                        calculation.setValue(multiply);
                        //单个面积
                        calculation.setArea(BigDecimal.valueOf(obj.getTotalArea()));
                        calculation.setGeom(obj.getGeom());
                        calculationList.add(calculation);
                    }
                }
            }
            //保存
            List<ResistEarthquakesPECalculation> conditionValue = getConditionValue(calculationList, tasks, rCalculation);
            //入库
            if (conditionValue.size() > 0) {
                resistEarthquakesPERepository.deleteCalculationByQuery(conditionValue.get(0));
                resistEarthquakesPERepository.batchCalculation(conditionValue);
            }
        } else {
            //单体数据
            List<BuildingIndividualEntity> all = calculationTasksRepository.getMonomerDate(tasks.getId());
            List<ResistEarthquakesPECalculation> conditionValue = new ArrayList<>();
            for (BuildingIndividualEntity obj : all) {
                //根据房屋单体经纬度获取对应发生概率
                List<PsHazardDataValue> psValue = new ArrayList<>();
                if (tasks.getSeismicInputMode().equals("3")) {
                    //根据房屋单体经纬度获取对应发生概率
                    psValue = publicOperateService.getFSGLbyLonAndLat(obj.getLongitude(), obj.getLatitude(), "1");
                } else {
                    //根据房屋单体经纬度获取对应超越概率
                    for (String rowKey : stringMapMap.rowKeySet()) {
                        Boolean boo = resistEarthquakesPERepository.getSTIntersects(rowKey, obj.getLongitude(), obj.getLatitude());
                        if (boo) {
                            Map<List<String>, List<BigDecimal>> row = stringMapMap.row(rowKey);
                            if (null == row) {
                            } else {
                                for (Map.Entry<List<String>, List<BigDecimal>> row1 : row.entrySet()) {
                                    for (int i = 0; i < row1.getKey().size(); i++) {
                                        PsHazardDataValue psHazardDataValue = new PsHazardDataValue();
                                        psHazardDataValue.setImValue(row1.getKey().get(i));
                                        psHazardDataValue.setFImValue(row1.getValue().get(i));
                                        psValue.add(psHazardDataValue);
                                    }
                                }
                            }
                            break;
                        }
                    }
                }
                //当前结构类型的概率计算值
                BigDecimal result = BigDecimal.ZERO;
                //总面积*设防占比之和
                BigDecimal totalArea = BigDecimal.ZERO;
                //破坏程度
                String damageDegree = dictService.getValueByDictCodeAndKey("pgcd", rCalculation.getDamageDegree());
                //将房屋单体转换成13VO
                Grid13VO grid13VO = get13VO(obj);
                //计算并将值赋给result,totalArea;
                List<BigDecimal> bigDecimals = calculationByFortification(grid13VO, psValue, obj.getStructureType1(), obj.getStructureType2(), damageDegree, result, totalArea, tasks);
                result = bigDecimals.get(0);
                totalArea = bigDecimals.get(1);
                //计算P(砖混)=S(砖混)*（P(VI)+P(VII)。。。+P(XII)）/S
                BigDecimal p = totalArea.multiply(result).divide(totalArea);
                ResistEarthquakesPECalculation pECalculation = new ResistEarthquakesPECalculation();
                //主键
                pECalculation.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                //评估记录id
                pECalculation.setAssessId(tasks.getId());
                pECalculation.setAssessCode(tasks.getAssessCode());
                //省市县
                pECalculation.setProvinceName(obj.getProvince());
                pECalculation.setCityName(obj.getCity());
                pECalculation.setCountyName(obj.getCounty());

                pECalculation.setGeographyId(obj.getId());
                //破坏状态
                pECalculation.setDamageDegree(rCalculation.getDamageDegree());
                //计算值
                pECalculation.setCalculatedValueP1(p);
                //修正值
                pECalculation.setCorrectionValueP1(p);
                //概率值p (T)
                pECalculation.setPt(p.multiply(BigDecimal.valueOf(Double.parseDouble(rCalculation.getYears()))));
                //T年
                pECalculation.setYears(rCalculation.getYears());
                //写入面积
                pECalculation.setArea(totalArea);
                pECalculation.setCreateUser(PlatformSessionContext.getUserID());
                pECalculation.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
                pECalculation.setDelFlag(YNEnum.N.toString());
                conditionValue.add(pECalculation);
            }
            //入库
            if (conditionValue.size() > 0) {
                resistEarthquakesPERepository.deleteCalculationByQuery(conditionValue.get(0));
                resistEarthquakesPERepository.batchCalculation(conditionValue);
            }
        }
    }

    //将房屋单体转换成Grid13VO
    private Grid13VO get13VO(BuildingIndividualEntity obj) {
        Grid13VO grid13VO = new Grid13VO();
        //写入面积
        grid13VO.setTotalArea(Double.valueOf(obj.getArea()));
        //写入设防占比
        grid13VO.setSfIntensity(0.00);
        grid13VO.setSfIntensity6(0.00);
        grid13VO.setSfIntensity7(0.00);
        grid13VO.setSfIntensity8(0.00);
        grid13VO.setSfIntensity9(0.00);
        if (obj.equals("0")) {
            grid13VO.setSfIntensity(100.00);
        } else if (obj.equals("6")) {
            grid13VO.setSfIntensity6(100.00);
        } else if (obj.equals("7")) {
            grid13VO.setSfIntensity7(100.00);
        } else if (obj.equals("8")) {
            grid13VO.setSfIntensity8(100.00);
        } else if (obj.equals("9")) {
            grid13VO.setSfIntensity9(100.00);
        }
        return grid13VO;
    }

    //获取房屋单体结构类型,将传入的类型转成汉字
    private String getType(String type1, String type2) {
        //获取类型
        String type = dictService.getValueByDictCodeAndKey("jglxyj", type1);
        if (null != type2) {
            String code = null;
            if (type1.equals("1")) {
                //砌体结构
                code = "qtjgej";
            } else if (type1.equals("2")) {
                //钢筋混凝土
                code = "gjhntjgej";
            } else if (type1.equals("6")) {
                //工业厂房
                code = "gycfej";
            }
            String valueByDictCodeAndKey = dictService.getValueByDictCodeAndKey(code, type2);
            type = type + "-" + valueByDictCodeAndKey;
        }
        return type;
    }


    //根据设防烈度计算
    private List<BigDecimal> calculationByFortification(Grid13VO obj, List<PsHazardDataValue> psHazardDataValues,
                                                        String dictItemCode, String damageDegree, BigDecimal result,
                                                        BigDecimal totalArea, CalculationTasks tasks, Map<String, Map<String, List<YSXMainTable>>> stringListMap) {
        ArrayList<BigDecimal> list = new ArrayList<>();
        //计算 计算的时候传入易损性数据
        Map<String, List<YSXMainTable>> stringListMap1 = stringListMap.get(obj.getProvince() + "_" + obj.getCity() + "_" + obj.getCounty());
        //结构类型_毁坏程度_烈度
                      /*  String structureTypeName = ySXUtil.getStructureType(dictItemCode);
                        String conditionName = ySXUtil.ldConversion(condition);
                        stringListMap1.get()*/
        //所有烈度
        for (PsHazardDataValue psHazardDataValue : psHazardDataValues) {
            if (PlatformObjectUtils.isEmpty(stringListMap1)) {
                continue;
            }
            String structureTypeName = ysxUtil.getStructureType(dictItemCode);
            //烈度转换
            String getImValue = convert2(psHazardDataValue.getImValue());
            String imValue = convert(getImValue);
            String conditionName = ysxUtil.ldConversion(imValue);
            List<YSXMainTable> ysxMainTables = stringListMap1.get(structureTypeName + damageDegree + conditionName);
            if (PlatformObjectUtils.isEmpty(ysxMainTables)) {
                continue;
            }
            Map<String, Double> ysxData = new HashMap<>();
            for (YSXMainTable entity : ysxMainTables) {
                ysxData.put(entity.getFortify(), Double.valueOf(entity.getRate().replace("%", "")));
            }
            //获取易损性
           /* Map<String, Double> ysxData = ySXUtil.getYSX(dictItemCode, damageDegree, imValue,
                    obj.getProvince(), obj.getCity(), obj.getCounty(), tasks.getId());*/
            //无易损性数据则则跳过计算
            if (ysxData.size() == 0) {
                continue;
            }
            //设防烈度为0的标记,如果为5则说明所有设防烈度都为0
            int fang = 0;
            //计算出各个设防的值
            //如果不设防不等于0
            if (obj.getSfIntensity() >= 0.0009) {
                //计算当前设防状态的面积
                //获取当前设防状态占比
                BigDecimal bigDecimal = BigDecimal.valueOf(obj.getSfIntensity()).divide(BigDecimal.valueOf(100)).setScale(8, BigDecimal.ROUND_DOWN);
                BigDecimal multiply = BigDecimal.valueOf(obj.getTotalArea()).multiply(bigDecimal);
                //根据条件获取易损性值所有烈度的
                BigDecimal gl2 = GLCalculate(ysxData.get("未设防"), psHazardDataValue.getFImValue());
                //所有防震等级都相加结果相加
                result = result.add(gl2);
                //面积
                totalArea = totalArea.add(multiply);
            } else {
                fang = fang + 1;
            }
            //如果现设防烈度_6度房屋面积占比不等于0
            if (obj.getSfIntensity6() >= 0.0009) {
                BigDecimal bigDecimal = BigDecimal.valueOf(obj.getSfIntensity6()).divide(BigDecimal.valueOf(100)).setScale(8, BigDecimal.ROUND_DOWN);
                BigDecimal multiply = BigDecimal.valueOf(obj.getTotalArea()).multiply(bigDecimal);
                BigDecimal gl2 = GLCalculate(ysxData.get("未设防"), psHazardDataValue.getFImValue());
                //所有防震等级都相加结果相加
                result = result.add(gl2);
                totalArea = totalArea.add(multiply);
            } else {
                fang = fang + 1;
            }
            //如果现设防烈度_7度房屋面积占比不等于0
            if (obj.getSfIntensity7() >= 0.0009) {
                BigDecimal bigDecimal = BigDecimal.valueOf(obj.getSfIntensity7()).divide(BigDecimal.valueOf(100)).setScale(8, BigDecimal.ROUND_DOWN);
                BigDecimal multiply = BigDecimal.valueOf(obj.getTotalArea()).multiply(bigDecimal);
                BigDecimal gl2 = GLCalculate(ysxData.get("未设防"), psHazardDataValue.getFImValue());
                //所有防震等级都相加结果相加
                result = result.add(gl2);
                totalArea = totalArea.add(multiply);
            } else {
                fang = fang + 1;
            }
            //如果现设防烈度_8度房屋面积占比不等于0
            if (obj.getSfIntensity8() >= 0.0009) {
                BigDecimal bigDecimal = BigDecimal.valueOf(obj.getSfIntensity8()).divide(BigDecimal.valueOf(100)).setScale(8, BigDecimal.ROUND_DOWN);
                BigDecimal multiply = BigDecimal.valueOf(obj.getTotalArea()).multiply(bigDecimal);
                BigDecimal gl2 = GLCalculate(ysxData.get("未设防"), psHazardDataValue.getFImValue());
                //所有防震等级都相加结果相加
                result = result.add(gl2);
                totalArea = totalArea.add(multiply);
            } else {
                fang = fang + 1;
            }
            //如果现设防烈度_9度房屋面积占比不等于0
            if (obj.getSfIntensity9() >= 0.0009) {
                BigDecimal bigDecimal = BigDecimal.valueOf(obj.getSfIntensity9()).divide(BigDecimal.valueOf(100)).setScale(8, BigDecimal.ROUND_DOWN);
                BigDecimal multiply = BigDecimal.valueOf(obj.getTotalArea()).multiply(bigDecimal);
                BigDecimal gl2 = GLCalculate(ysxData.get("未设防"), psHazardDataValue.getFImValue());
                //所有防震等级都相加结果相加
                result = result.add(gl2);
                totalArea = totalArea.add(multiply);
            } else {
                fang = fang + 1;
            }
            //如果没有一个设防结构有值则默认为未设防100%,并且在有总面积的时候计算
            if (fang == 5 & obj.getTotalArea() >= 0.01) {
                BigDecimal bigDecimal = BigDecimal.valueOf(obj.getTotalArea());
                //根据条件获取易损性值
                BigDecimal gl2 = GLCalculate(ysxData.get("未设防"), psHazardDataValue.getFImValue());
                //所有防震等级都相加结果相加
                result = result.add(gl2);
                totalArea = totalArea.add(bigDecimal);
            }
        }
        list.add(result);
        list.add(totalArea);
        return list;
    }

    private List<BigDecimal> calculationByFortification(Grid13VO obj, List<PsHazardDataValue> psHazardDataValues,
                                                        String type1, String type2, String damageDegree, BigDecimal result,
                                                        BigDecimal totalArea, CalculationTasks tasks) {
        ArrayList<BigDecimal> list = new ArrayList<>();

        //所有烈度
        for (PsHazardDataValue psHazardDataValue : psHazardDataValues) {
            //烈度转换
            String getImValue = convert2(psHazardDataValue.getImValue());
            String imValue = convert(getImValue);
            //获取易损性
            Map<String, Double> ysxData = ysxUtil.getYSX(type1, type2, damageDegree, imValue,
                    obj.getProvince(), obj.getCity(), obj.getCounty(), tasks.getId());
            //设防烈度为0的标记,如果为5则说明所有设防烈度都为0
            int fang = 0;
            //计算出各个设防的值
            //如果不设防不等于0
            if (obj.getSfIntensity() >= 0.0009) {
                //计算当前设防状态的面积
                //获取当前设防状态占比
                BigDecimal bigDecimal = BigDecimal.valueOf(obj.getSfIntensity()).divide(BigDecimal.valueOf(100)).setScale(8, BigDecimal.ROUND_DOWN);
                BigDecimal multiply = BigDecimal.valueOf(obj.getTotalArea()).multiply(bigDecimal);
                //根据条件获取易损性值所有烈度的
                BigDecimal gl2 = GLCalculate(ysxData.get("未设防"), psHazardDataValue.getFImValue());
                //所有防震等级都相加结果相加
                result = result.add(gl2);
                //面积
                totalArea = totalArea.add(multiply);
            } else {
                fang = fang + 1;
            }
            //如果现设防烈度_6度房屋面积占比不等于0
            if (obj.getSfIntensity6() >= 0.0009) {
                BigDecimal bigDecimal = BigDecimal.valueOf(obj.getSfIntensity6()).divide(BigDecimal.valueOf(100)).setScale(8, BigDecimal.ROUND_DOWN);
                BigDecimal multiply = BigDecimal.valueOf(obj.getTotalArea()).multiply(bigDecimal);
                BigDecimal gl2 = GLCalculate(ysxData.get("未设防"), psHazardDataValue.getFImValue());
                //所有防震等级都相加结果相加
                result = result.add(gl2);
                totalArea = totalArea.add(multiply);
            } else {
                fang = fang + 1;
            }
            //如果现设防烈度_7度房屋面积占比不等于0
            if (obj.getSfIntensity7() >= 0.0009) {
                BigDecimal bigDecimal = BigDecimal.valueOf(obj.getSfIntensity7()).divide(BigDecimal.valueOf(100)).setScale(8, BigDecimal.ROUND_DOWN);
                BigDecimal multiply = BigDecimal.valueOf(obj.getTotalArea()).multiply(bigDecimal);
                BigDecimal gl2 = GLCalculate(ysxData.get("未设防"), psHazardDataValue.getFImValue());
                //所有防震等级都相加结果相加
                result = result.add(gl2);
                totalArea = totalArea.add(multiply);
            } else {
                fang = fang + 1;
            }
            //如果现设防烈度_8度房屋面积占比不等于0
            if (obj.getSfIntensity8() >= 0.0009) {
                BigDecimal bigDecimal = BigDecimal.valueOf(obj.getSfIntensity8()).divide(BigDecimal.valueOf(100)).setScale(8, BigDecimal.ROUND_DOWN);
                BigDecimal multiply = BigDecimal.valueOf(obj.getTotalArea()).multiply(bigDecimal);
                BigDecimal gl2 = GLCalculate(ysxData.get("未设防"), psHazardDataValue.getFImValue());
                //所有防震等级都相加结果相加
                result = result.add(gl2);
                totalArea = totalArea.add(multiply);
            } else {
                fang = fang + 1;
            }
            //如果现设防烈度_9度房屋面积占比不等于0
            if (obj.getSfIntensity9() >= 0.0009) {
                BigDecimal bigDecimal = BigDecimal.valueOf(obj.getSfIntensity9()).divide(BigDecimal.valueOf(100)).setScale(8, BigDecimal.ROUND_DOWN);
                BigDecimal multiply = BigDecimal.valueOf(obj.getTotalArea()).multiply(bigDecimal);
                BigDecimal gl2 = GLCalculate(ysxData.get("未设防"), psHazardDataValue.getFImValue());
                //所有防震等级都相加结果相加
                result = result.add(gl2);
                totalArea = totalArea.add(multiply);
            } else {
                fang = fang + 1;
            }
            //如果没有一个设防结构有值则默认为未设防100%,并且在有总面积的时候计算
            if (fang == 5 & obj.getTotalArea() >= 0.01) {
                BigDecimal bigDecimal = BigDecimal.valueOf(obj.getTotalArea());
                //根据条件获取易损性值
                BigDecimal gl2 = GLCalculate(ysxData.get("未设防"), psHazardDataValue.getFImValue());
                //所有防震等级都相加结果相加
                result = result.add(gl2);
                totalArea = totalArea.add(bigDecimal);
            }
        }
        list.add(result);
        list.add(totalArea);
        return list;
    }

    //13个计算值归并计算
    private List<ResistEarthquakesPECalculation> getConditionValue(List<Calculation> calculationList, CalculationTasks tasks, ResistEarthquakesPECalculation rCalculation) {
        ArrayList<ResistEarthquakesPECalculation> list = new ArrayList<>();
        Map<String, List<Calculation>> map = new HashMap<>();
        //将获得的所有数据进行归并,从而获得每个一样的geom下的所有计算值,并进行计算
        for (Calculation calculation : calculationList) {
            String extends1 = calculation.getExtends1();
            List<Calculation> newList;
            if (map.containsKey(extends1)) {
                newList = map.get(extends1);
            } else {
                newList = new ArrayList<>();
            }
            newList.add(calculation);
            map.put(extends1, newList);
        }
        for (Map.Entry<String, List<Calculation>> entry : map.entrySet()) {
            List<Calculation> value = entry.getValue();
            BigDecimal p1 = BigDecimal.ZERO;
            BigDecimal v1 = BigDecimal.ZERO;
            BigDecimal v2 = BigDecimal.ZERO;
            BigDecimal v3 = BigDecimal.ZERO;
            BigDecimal v4 = BigDecimal.ZERO;
            BigDecimal area = BigDecimal.ZERO;
            for (Calculation calculation : value) {
                //获取格网总面积
                area = area.add(calculation.getArea());
            }
            //如果是pga则是四个破坏状态一起算
            if (tasks.getLdPga().equals("1")) {
                for (Calculation calculation : value) {
                    BigDecimal t1 = null;
                    BigDecimal t2 = null;
                    BigDecimal t3 = null;
                    BigDecimal t4 = null;
                    //S(砖混)*【0.999969*（f1(0.01）-f2(0.01))+0.961678*（f1(0.15）-f2(0.15))+。。。+0.0012*（f1(0.95）-f2(0.95))】/S
                    if (area.toString().equals("0")) {
                        t1 = BigDecimal.ZERO;
                        t2 = BigDecimal.ZERO;
                        t3 = BigDecimal.ZERO;
                        t4 = BigDecimal.ZERO;
                    } else {
                        if (Double.parseDouble(calculation.getV1().toString()) < 0.00001) {
                            t1 = BigDecimal.ZERO;
                        } else {
                            t1 = calculation.getV1().divide(area, 4, BigDecimal.ROUND_DOWN).setScale(4, BigDecimal.ROUND_DOWN);
                        }
                        if (Double.parseDouble(calculation.getV2().toString()) < 0.00001) {
                            t2 = BigDecimal.ZERO;
                        } else {
                            t2 = calculation.getV2().divide(area, 4, BigDecimal.ROUND_DOWN).setScale(4, BigDecimal.ROUND_DOWN);
                        }
                        if (Double.parseDouble(calculation.getV3().toString()) < 0.00001) {
                            t3 = BigDecimal.ZERO;
                        } else {
                            t3 = calculation.getV3().divide(area, 4, BigDecimal.ROUND_DOWN).setScale(4, BigDecimal.ROUND_DOWN);
                        }
                        if (Double.parseDouble(calculation.getV4().toString()) < 0.00001) {
                            t4 = BigDecimal.ZERO;
                        } else {
                            t4 = calculation.getV4().divide(area, 4, BigDecimal.ROUND_DOWN).setScale(4, BigDecimal.ROUND_DOWN);
                        }
                    }
                    //p(1)=P(砖混)+P(钢结构)+。。。。。
                    v1 = v1.add(t1);
                    v2 = v2.add(t2);
                    v3 = v3.add(t3);
                    v4 = v4.add(t4);
                }
                //写入list
                ArrayList<BigDecimal> list1 = new ArrayList<>();
                list1.add(v1);
                list1.add(v2);
                list1.add(v3);
                list1.add(v4);
                for (int i = 0; i < list1.size(); i++) {
                    BigDecimal bigDecimal = list1.get(i);
                    ResistEarthquakesPECalculation obj = new ResistEarthquakesPECalculation();
                    //主键
                    obj.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                    //评估记录id
                    obj.setAssessId(tasks.getId());
                    obj.setAssessCode(tasks.getAssessCode());
                    //省市县
                    obj.setProvinceName(value.get(0).getProvince());
                    obj.setCityName(value.get(0).getCity());
                    obj.setCountyName(value.get(0).getCounty());
                    //格网id
                    obj.setExtends1(value.get(0).getExtends1());
                    obj.setGeographyId(value.get(0).getExtends1());
                    //破坏状态
                    obj.setDamageDegree("pgcd" + (i + 1));
                    //计算值
                    obj.setCalculatedValueP1(bigDecimal);
                    //修正值
                    obj.setCorrectionValueP1(bigDecimal);
                    //概率值p (T)
                    obj.setPt(bigDecimal.multiply(BigDecimal.valueOf(Double.parseDouble(rCalculation.getYears()))));
                    //T年
                    obj.setYears(rCalculation.getYears());
                    //geom
                    obj.setGeom(calculationList.get(0).getGeom());
                    //写入面积
                    obj.setArea(area);
                    obj.setCreateUser(PlatformSessionContext.getUserID());
                    obj.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
                    obj.setDelFlag(YNEnum.N.toString());
                    list.add(obj);
                }
            } else {
                for (Calculation calculation : value) {
                    BigDecimal divide = null;
                    //P(砖混)=S(砖混)*（P(VI)+P(VII)。。。+P(XII)））/S
                    if (area.toString().equals("0")) {
                        divide = BigDecimal.ZERO;
                    } else {
                        if (Double.parseDouble(calculation.getValue().toString()) < 0.00001) {
                            divide = BigDecimal.ZERO;
                        } else {
                            divide = calculation.getValue().divide(area, 4, BigDecimal.ROUND_DOWN).setScale(4, BigDecimal.ROUND_DOWN);
                        }
                    }
                    //p(1)=P(砖混)+P(钢结构)+。。。。。
                    p1 = p1.add(divide);
                }
                ResistEarthquakesPECalculation obj = new ResistEarthquakesPECalculation();
                //主键
                obj.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                //评估记录id
                obj.setAssessId(tasks.getId());
                obj.setAssessCode(tasks.getAssessCode());
                //省市县
                obj.setProvinceName(value.get(0).getProvince());
                obj.setCityName(value.get(0).getCity());
                obj.setCountyName(value.get(0).getCounty());
                //格网id
                obj.setExtends1(value.get(0).getExtends1());
                obj.setGeographyId(value.get(0).getExtends1());
                //破坏状态
                obj.setDamageDegree(rCalculation.getDamageDegree());
                //计算值
                obj.setCalculatedValueP1(p1);
                //修正值
                obj.setCorrectionValueP1(p1);
                //概率值p (T)
                obj.setPt(p1.multiply(BigDecimal.valueOf(Double.parseDouble(rCalculation.getYears()))));
                //T年
                obj.setYears(rCalculation.getYears());
                //geom
                obj.setGeom(calculationList.get(0).getGeom());
                //写入面积
                obj.setArea(area);
                obj.setCreateUser(PlatformSessionContext.getUserID());
                obj.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
                obj.setDelFlag(YNEnum.N.toString());
                list.add(obj);
            }

        }
        return list;
    }


    //概率计算
    private BigDecimal GLCalculate(Double ysxValue, BigDecimal fImValue) {
        BigDecimal ysxnum = BigDecimal.valueOf(ysxValue).divide(BigDecimal.valueOf(100));
        //计算概率 -ln(1-发生概率)*易损性
        BigDecimal x = BigDecimal.valueOf(1).subtract(fImValue);
        //概率
        BigDecimal gl = BigDecimal.valueOf(-Math.log(x.doubleValue())).setScale(6, RoundingMode.DOWN);
        //概率
        BigDecimal gl2 = gl.multiply(ysxnum);
        return gl2;
    }

    private String convert2(String imValue) {
        if (null == imValue) {
            return null;
        }
        switch (imValue) {
            case "Ⅴ":
                return "V";
            case "Ⅵ":
                return "VI";
            case "Ⅶ":
                return "VII";
            case "Ⅷ":
                return "VIII";
            case "Ⅸ":
                return "IX";
            case "Ⅹ":
                return "X";
            case "Ⅺ":
                return "XI";
            case "Ⅻ":
                return "XII";
        }
        return null;
    }

    //将超越概率的烈度转换成字典值
    private String convert(String imValue) {
        if (null == imValue) {
            return null;
        }
        switch (imValue) {
            case "V":
                return "ld1";
            case "VI":
                return "ld1";
            case "VII":
                return "ld2";
            case "VIII":
                return "ld3";
            case "IX":
                return "ld4";
            case "X":
                return "ld5";
            case "XI":
                return "ld5";
            case "XII":
                return "ld5";
        }
        return null;
    }

    //导入
    @Override
    public String reportImport(InputStream inputStream, String type, String id, String years) {
        Workbook workbook = null;
        try {
            workbook = WorkbookFactory.create(inputStream);

            Map<String, Object> map = getList(workbook, type, id, years);
            Object o = map.get("message");
            if (o != null) {
                return String.valueOf(o);
            } else {
                List<ResistEarthquakesPECalculation> list = (List<ResistEarthquakesPECalculation>) map.get("list");
                resistEarthquakesPERepository.batchCalculation1(list);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "成功";
    }

    //导出
    @Override
    public void exportData(HttpServletResponse response, ResistEarthquakesPECalculationParam param) {
        // CalculationTasks byId = calculationTasksRepository.findById(param.getId());
        //查询省市县
        List<ResistEarthquakesPCCPEVO> list = resistEarthquakesPERepository.getListPCC(param);
        try {
            EasyPoiExcelUtil.exportExcel(list, "计算值", "计算值", ResistEarthquakesPCCPEVO.class, "抗震能力概率评估计算.xlsx", response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //根据条件查询计算值
    @Override
    public Map<String, Object> queryCalculation(int curPage, int pageSize, String id, String years, String damageDegree) {
        return resistEarthquakesPERepository.queryCalculation(curPage, pageSize, id, years, damageDegree);
    }

    @Override
    public List<ResistEarthquakesPECalculation> queryCalculation1(String assessId) {
        return resistEarthquakesPERepository.queryCalculation1(assessId);
    }

    @Override
    public void updateCorrectionValue(ResistEarthquakesPECalculation param) {
        //param.setPt(param.getCorrectionValueP1().multiply(new BigDecimal(param.getYears())));
        resistEarthquakesPERepository.updateCorrectionValue(param);
    }

    @Resource
    private Tools tools;
    @Resource
    private JcsjRestManager jcsjRestManager;

    @Override
    public List<FxqhAssessPdQhResult> doZoning(CalculationTasks task) throws BizException, UnsupportedEncodingException {
        List<FxqhAssessPdQhResult> resultList = new ArrayList<>();
        Map<String, String> areaIdCodeMap = (Map<String, String>) JSON.parse((String) redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaIdCodeMap"));
        List<PCC> pccList = null;
//        if (task.getRadio2().equals("0")) {
        pccList = task.getList();
//        } else {
//            pccList = pccRepository.queryToponym(task.getId());
//        }
        String seiMode = null;
        if (task.getSeismicInputMode().contains("3")) {
            //发生概率
            seiMode = "0";
        } else if (task.getSeismicInputMode().contains("4")) {
            //超越概率
            seiMode = "1";
        } else {
            throw new RuntimeException("没有概率评估，不能进行概率评估风险区划！");
        }
        Map<String, Map<String, List<Map<String, Object>>>> listMapMap = new HashMap<>();
        Map<String, List<Map<String, Object>>> listMap = null;
        List<Map<String, Object>> mapList = null;
        List<Map<String, Object>> list = resistEarthquakesPERepository.getSumByTaskId(task.getId());
        if(PlatformObjectUtils.isNotEmpty(list) &&list.size()>0){
            for (Map<String, Object> map : list) {
                String key1 = map.get("provinceName") + "-" + map.get("cityName") + "-" + map.get("countyName");
                if (listMapMap.containsKey(key1)) {
                    listMap = listMapMap.get(key1);
                } else {
                    listMap = new HashMap<>();
                }
                if (listMap.containsKey(map.get("years") + "")) {
                    mapList = listMap.get(map.get("years") + "");
                } else {
                    mapList = new ArrayList<>();
                }
                mapList.add(map);
                listMap.put(map.get("years") + "", mapList);
                listMapMap.put(key1, listMap);
            }
        }

//         for (String seiMode : task.getSeismicInputMode().split(",")) {
//             if (!seiMode.equals("3")) {
//                 continue;
//             }
        Map<String, List<Map<String, Object>>> listMap1 = null;
        List<Map<String, Object>> mapList1 = null;
        if(listMapMap.values().size()>0){
            for (PCC pcc : pccList) {
                listMap1 = listMapMap.get(pcc.getPpName() + "-" + pcc.getCityName() + "-" + pcc.getName());
                String divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(pcc.getPpName(), "UTF-8"),
                        URLEncoder.encode(pcc.getCityName(), "UTF-8"), URLEncoder.encode(pcc.getName(), "UTF-8"));
                String code = null;
                if (areaIdCodeMap == null || areaIdCodeMap.size() < 1) {
                    code = sysAreaService.getDivisionCodeById(divisionIds.split("_")[2]);
                } else {
                    code = areaIdCodeMap.get(divisionIds.split("_")[2]);
                }
                String geom = jcsjRestManager.getGeomByCode(code, "3");
                if (geom == null) {
                    continue;
                    // throw new RuntimeException("未获取到" + pcc.getPpName() + pcc.getCityName() + pcc.getName() + "的空间数据！");
                }
                for (String years : task.getYear().split(",")) {
                    if (years.equals("undefined")) {
                        continue;
                    }
                    mapList1 = listMap1.get(years);
                    // Map<String, Map<String, List<BuildingVulnerability>>> ysxData = tools.getYSX(pcc.getPpName(), pcc.getCityName(), pcc.getName());
                    // List<Map<String, Object>> list = resistEarthquakesPERepository.getSumByDivisionAndAssessCodes(pcc.getPpName(), pcc.getCityName(), pcc.getName(),
                    //         task.getId(), condition);
                    // String extends1 = "";
                    BigDecimal sumArea = BigDecimal.ZERO;
                    BigDecimal calculatedValue = BigDecimal.ZERO;
                    for (int i = 0; i < mapList1.size(); i++) {
                        Map<String, Object> map = mapList1.get(i);
                        String damageDegree = (String) map.get("damageDegree");
                        //BigDecimal.valueOf(Double.valueOf(map.get("area")));
                        BigDecimal area = BigDecimal.ZERO;
                        if (PlatformObjectUtils.isNotEmpty(map.get("area"))) {
                            area = new BigDecimal(map.get("area") + "");
                        }
                        switch (damageDegree) {
                            case "pgcd4":
                            case "pgcd5":
                                calculatedValue = calculatedValue.add(BigDecimal.valueOf((Double) map.get("sum")).multiply(area));
                                break;
                        }
                        sumArea = sumArea.add(area);
                        // if (!extends1.equals((String) map.get("extends1"))) {
                        //     calculatedValue = BigDecimal.ZERO;
                        // }
                        // extends1 = (String) map.get("extends1");
                        // calculatedValue=calculatedValue.add(BigDecimal.valueOf((Double)map.get("sum")));
                    }
                    FxqhAssessPdQhResult result = new FxqhAssessPdQhResult();
                    result.setProvince(pcc.getPpName());
                    result.setCity(pcc.getCityName());
                    result.setCounty(pcc.getName());
                    if ("新疆维吾尔自治区".equals(pcc.getPpName()) || "青海省".equals(pcc.getPpName()) || "西藏自治区".equals(pcc.getPpName())) {
                        result.setBorderlandFlag("1");
                    } else {
                        result.setBorderlandFlag("0");
                    }
                    if (mapList1.size() > 0 && BigDecimal.ZERO.compareTo(sumArea) != 0) {
                        result.setCalculatedValue(calculatedValue.divide(sumArea, 8, BigDecimal.ROUND_UP));
                    } else {
                        result.setCalculatedValue(BigDecimal.ZERO);
                    }
                    result.setGeom(geom);
                    result.setId(UUIDGenerator.getUUID());
                    result.setTaskId(task.getId());
                    result.setEstimateObj("0");
                    result.setHouseDataFlag(task.getHouseDataFlag());
                    result.setCondition(years);
                    result.setSeismicInputMode(seiMode);
                    resultList.add(result);
                }
            }
        }

        // }
        return resultList;
    }

    //获取list
//    private Map<String, Object> getList(Workbook workbook, String type, String id, String years) throws UnsupportedEncodingException {
//        String userID = PlatformSessionContext.getUserID();
//        Map<String, Object> map = new HashMap<>();
//        List<ResistEarthquakesPECalculation> list = new ArrayList<>();
//        Boolean mark = true;
//        if (type.equals("2")) {
//            mark = false;
//        }
//        if (workbook != null) {
//            //循环除了第一行的所有行
//            /** 得到第一个sheet */
//            Sheet sheet = workbook.getSheetAt(0);
//            /** 得到Excel的行数 */
//            int totalRows = sheet.getPhysicalNumberOfRows();
//            HSSFDataFormatter hSSFDataFormatter = new HSSFDataFormatter();
//            /** 循环Excel的行 从第4行开始*/
//            for (int r = 3; r < totalRows; r++) {
//                Row row = sheet.getRow(r);
//                if (row == null) {
//                    continue;
//                }
//                ResistEarthquakesPECalculation obj = new ResistEarthquakesPECalculation();
//                if (mark) {
//                    //按照省市县输入时校验
//                    Map<String, Object> check = check(row);
//                    //如果没有message
//                    if (check.get("message") == null) {
//                        //省
//                        obj.setProvinceName(hSSFDataFormatter.formatCellValue(row.getCell(0)));
//                        //市
//                        obj.setCityName(hSSFDataFormatter.formatCellValue(row.getCell(1)));
//                        //县
//                        obj.setCountyName(hSSFDataFormatter.formatCellValue(row.getCell(2)));
//                        //建筑物公里网格ID（建筑物单体ID）
//                        obj.setGeographyId(hSSFDataFormatter.formatCellValue(row.getCell(3)));
//                        //破坏程度(轻微,中等,严重,倒塌)
//                        obj.setExtreme(hSSFDataFormatter.formatCellValue(row.getCell(4)));
//                        //概率P(t)计算值
//                        BigDecimal calculatedValue = new BigDecimal(hSSFDataFormatter.formatCellValue(row.getCell(5)));
//                        BigDecimal calculatedValue1 = new BigDecimal(hSSFDataFormatter.formatCellValue(row.getCell(6)));
//                        obj.setCalculatedValueP1(calculatedValue);
//                        //概率P(t)修正值
//                        obj.setCorrectionValueP1(calculatedValue1);
//                    } else {
//                        return check;
//                    }
//                } else {
//                    //按照坐标范围输入时校验
//                    Map<String, Object> check = check2(row);
//                    //如果没有message
//                    if (check.get("message") == null) {
//                        //经纬度坐标范围
//                        obj.setCoordinateRange(hSSFDataFormatter.formatCellValue(row.getCell(0)));
//                        //建筑物公里网格ID（建筑物单体ID）
//                        obj.setGeographyId(hSSFDataFormatter.formatCellValue(row.getCell(1)));
//                        //破坏程度(轻微,中等,严重,倒塌)
//                        obj.setExtreme(hSSFDataFormatter.formatCellValue(row.getCell(2)));
//                        //概率P(t)计算值
//                        BigDecimal calculatedValue = new BigDecimal(hSSFDataFormatter.formatCellValue(row.getCell(4)));
//                        BigDecimal calculatedValue1 = new BigDecimal(hSSFDataFormatter.formatCellValue(row.getCell(5)));
//                        obj.setCalculatedValueP1(calculatedValue);
//                        //概率P(t)修正值
//                        obj.setCorrectionValueP1(calculatedValue1);
//                    } else {
//                        return check;
//                    }
//                }
//                //评估记录id
//                obj.setAssessId(id);
//                //主键id
//                obj.setId(UUID.randomUUID().toString().replaceAll("-", ""));
//                //创建人
//                obj.setCreateUser(userID);
//                //创建时间
//                obj.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
//                //T年
//                obj.setYears(years);
//                list.add(obj);
//            }
//        }
//        map.put("list", list);
//        return map;
//    }
    private Map<String, Object> getList(Workbook workbook, String type, String id, String years) throws UnsupportedEncodingException {
        CalculationTasks byId = calculationTasksRepository.findById(id);
        String userID = PlatformSessionContext.getUserID();
        Map<String, Object> map = new HashMap<>();
        List<ResistEarthquakesPECalculation> list = new ArrayList<>();
        Boolean mark = true;
        if (type.equals("2")) {
            mark = true;
        }
        if (workbook != null) {
            //循环除了第一行的所有行
            /** 得到第一个sheet */
            Sheet sheet = workbook.getSheetAt(0);
            /** 得到Excel的行数 */
            int totalRows = sheet.getPhysicalNumberOfRows();
            HSSFDataFormatter hSSFDataFormatter = new HSSFDataFormatter();
            /** 循环Excel的行 从第4行开始*/
            for (int r = 2; r < totalRows; r++) {
                Row row = sheet.getRow(r);
                if (row == null) {
                    continue;
                }
                ResistEarthquakesPECalculation obj = new ResistEarthquakesPECalculation();
                if (mark) {
                    //按照省市县输入时校验
                    Map<String, Object> check = check(row);
                    //如果没有message
                    if (check.get("message") == null) {
                        //省
                        obj.setProvinceName(hSSFDataFormatter.formatCellValue(row.getCell(0)));
                        //市
                        obj.setCityName(hSSFDataFormatter.formatCellValue(row.getCell(1)));
                        //县
                        obj.setCountyName(hSSFDataFormatter.formatCellValue(row.getCell(2)));
                        //建筑物公里网格ID（建筑物单体ID）
                        obj.setGeographyId(hSSFDataFormatter.formatCellValue(row.getCell(3)));
                        //年
                        obj.setYears(hSSFDataFormatter.formatCellValue(row.getCell(4)));
                        //破坏程度(轻微,中等,严重,倒塌)
                        //破坏程度(轻微,中等,严重,倒塌)
                        String damageDegree = hSSFDataFormatter.formatCellValue(row.getCell(5));
                        if("基本完好".equals(damageDegree)){
                            damageDegree  = "pgcd1";
                        }else if("轻微破坏".equals(damageDegree)){
                            damageDegree  = "pgcd2";
                        }else if("中等破坏".equals(damageDegree)){
                            damageDegree  = "pgcd3";
                        }else if("严重破坏".equals(damageDegree)){
                            damageDegree  = "pgcd4";
                        }else if("倒塌".equals(damageDegree)){
                            damageDegree  = "pgcd5";
                        }
                        obj.setDamageDegree(damageDegree);
                        //概率P(t)计算值
                        BigDecimal calculatedValue = new BigDecimal(hSSFDataFormatter.formatCellValue(row.getCell(6)));
                        BigDecimal calculatedValue1 = new BigDecimal(hSSFDataFormatter.formatCellValue(row.getCell(7)));
                        obj.setPt(calculatedValue);
                        //概率P(t)修正值
                        obj.setCorrectionValuePt(calculatedValue1);
                    } else {
                        return check;
                    }
                } else {
                    //按照坐标范围输入时校验
                    Map<String, Object> check = check2(row);
                    //如果没有message
                    if (check.get("message") == null) {
                        //经纬度坐标范围
                        obj.setCoordinateRange(hSSFDataFormatter.formatCellValue(row.getCell(0)));
                        //建筑物公里网格ID（建筑物单体ID）
                        obj.setGeographyId(hSSFDataFormatter.formatCellValue(row.getCell(1)));
                        //破坏程度(轻微,中等,严重,倒塌)
                        String damageDegree = hSSFDataFormatter.formatCellValue(row.getCell(2));
                        if("基本完好".equals(damageDegree)){
                            damageDegree  = "pgcd1";
                        }else if("轻微破坏".equals(damageDegree)){
                            damageDegree  = "pgcd2";
                        }else if("中等破坏".equals(damageDegree)){
                            damageDegree  = "pgcd3";
                        }else if("严重破坏".equals(damageDegree)){
                            damageDegree  = "pgcd4";
                        }else if("倒塌".equals(damageDegree)){
                            damageDegree  = "pgcd5";
                        }
                        obj.setDamageDegree(damageDegree);
                        //概率P(t)计算值
                        BigDecimal calculatedValue = new BigDecimal(hSSFDataFormatter.formatCellValue(row.getCell(4)));
                        BigDecimal calculatedValue1 = new BigDecimal(hSSFDataFormatter.formatCellValue(row.getCell(5)));
                        obj.setPt(calculatedValue);
                        //概率P(t)修正值
                        obj.setCorrectionValuePt(calculatedValue1);
                    } else {
                        return check;
                    }
                }
                //评估记录id
                obj.setAssessId(id);
                obj.setAssessCode(byId.getAssessCode());
                //主键id
                obj.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                //创建人
                obj.setCreateUser(userID);
                //创建时间
                obj.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
                //T年
//                obj.setYears(years);
                obj.setExtends1(obj.getGeographyId());
                list.add(obj);
            }
        }
        map.put("list", list);
        return map;
    }

    //数据校验省市县
    private Map<String, Object> check(Row row) throws UnsupportedEncodingException {
        HashMap<String, Object> map = new HashMap<>();
        HSSFDataFormatter hSSFDataFormatter = new HSSFDataFormatter();
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(0)))) {
            map.put("message", "省不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(1)))) {
            map.put("message", "市不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(2)))) {
            map.put("message", "县不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(3)))) {
            map.put("message", "建筑物公里网格ID（建筑物单体ID）不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(4)))) {
            map.put("message", "极限不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(5)))) {
            map.put("message", "概率P（1）计算值不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(6)))) {
            map.put("message", "概率P（1）修正值不能为空");
        }
        String province = hSSFDataFormatter.formatCellValue(row.getCell(0));
        String city = hSSFDataFormatter.formatCellValue(row.getCell(1));
        String county = hSSFDataFormatter.formatCellValue(row.getCell(2));
        // 根据省市县名称获得省市县id _ 分割
        String divisionIds = sysAreaService.getIdByCondition(
                URLEncoder.encode(province, "UTF-8"),
                URLEncoder.encode(city, "UTF-8"),
                URLEncoder.encode(county, "UTF-8"));
        if (divisionIds == null) {
            map.put("message", "省市县错误" + province + "_" + city + "_" + county);
        }
        String[] s = divisionIds.split("_");
        if (s.length != 3) {
            map.put("message", "省市县错误" + province + "_" + city + "_" + county);
        }
        return map;
    }

    //范围校验
    private Map<String, Object> check2(Row row) throws UnsupportedEncodingException {
        HashMap<String, Object> map = new HashMap<>();
        HSSFDataFormatter hSSFDataFormatter = new HSSFDataFormatter();
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(0)))) {
            map.put("message", "坐标范围不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(1)))) {
            map.put("message", "建筑物公里网格ID（建筑物单体ID）不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(2)))) {
            map.put("message", "极限不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(3)))) {
            map.put("message", "概率P（1）计算值不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(4)))) {
            map.put("message", "概率P（1）修正值不能为空");
        }
        return map;
    }
}
